package cn.xo68.boot.auth.server.service;

import cn.xo68.boot.auth.core.common.AuthConstants;
import cn.xo68.boot.auth.server.domain.OauthRoleResource;
import cn.xo68.boot.auth.server.mapper.OauthRoleResourceMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * OauthRoleResource Service
 * @author wuyy(16349023@qq.com)
 * @date 2018年08月28日 11:04:12
 *
 */
@CacheConfig(cacheNames = {AuthConstants.CACHE_NAME_OAUTH2_ROLE_RESOURCE})
 @Service
public class OauthRoleResourceService{
    @Autowired
    private OauthRoleResourceMapper oauthRoleResourceMapper;

    public OauthRoleResource get(String serialId) {
        return  oauthRoleResourceMapper.get(serialId);
    }

    @Cacheable(key = "#clientId+'-'+#roleId",unless = "#result == null")
    public List<String> listRoleResourcs(String roleId,String clientId){
        return oauthRoleResourceMapper.listRoleResourcs(roleId,clientId);
    }

    /**
     * 保存 指定应用 角色资源
     * @param clientId
     * @param roleId
     * @param resources
     */
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void saveResources(String clientId, String roleId,List<OauthRoleResource> resources){
        oauthRoleResourceMapper.delete(clientId, roleId);
        for (OauthRoleResource resource : resources){
            oauthRoleResourceMapper.insert(resource);
        }
    }

    public void insert(OauthRoleResource oauthRoleResource) {
        oauthRoleResourceMapper.insert(oauthRoleResource);
    }

    public void update(OauthRoleResource oauthRoleResource) {
        oauthRoleResourceMapper.update(oauthRoleResource);
    }

    public List<OauthRoleResource> list() {
        return oauthRoleResourceMapper.list();
    }
	
	public PageInfo<OauthRoleResource> list(int pageNumber,int pageSize) {
        PageHelper.startPage(pageNumber, pageSize,true);
        List<OauthRoleResource> docs = oauthRoleResourceMapper.list();
        PageInfo<OauthRoleResource> pageInfo = new PageInfo<>(docs);
        return pageInfo;
    }
}